package com.icez.demo

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView

/**
 * 圆形按钮
 * @sample
 * @author Icez
 */
class CircleButton @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : AppCompatImageView(context, attrs) {
    private val mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var mBorderWidth: Float = 1f
    private var mBorderColor: Int = Color.RED
    private var mPressedBorderColor = Color.YELLOW

    init {


        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.CircleButton)
        mBorderWidth =
            typedArray.getDimensionPixelSize(R.styleable.CircleButton_borderWidth, 1).toFloat()
        mBorderColor = typedArray.getColor(R.styleable.CircleButton_borderColor, Color.RED)
        mPressedBorderColor = typedArray.getColor(R.styleable.CircleButton_bgColor, Color.YELLOW)
        typedArray.recycle()

        mPaint.strokeWidth = mBorderWidth
    }

    /**
     * 设置属性
     *
     * @param mBorderWidth
     * @param mBorderColor
     * @param mBgColor
     */
    fun setAttrs(mBorderWidth: Float = 1f, mBorderColor: Int = Color.RED, mBgColor: Int = Color.YELLOW) {
        this.mBorderWidth = mBorderWidth
        this.mBorderColor = mBorderColor
        this.mPressedBorderColor = mBgColor
        invalidate()
    }

    /**
     * 计算控件的大小；把控件绘制成正方形
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val height = MeasureSpec.getSize(heightMeasureSpec)
        val width = MeasureSpec.getSize(widthMeasureSpec)
        var size = height
        if (size > width) {
            size = width
        }
        setMeasuredDimension(size, size)
    }

    override fun onDraw(canvas: Canvas?) {
        val radius = width / 2f
        mPaint.color = mBorderColor
        mPaint.style = Paint.Style.STROKE
        canvas?.drawCircle(radius, radius, radius - (mBorderWidth / 2f), mPaint)
        if (isPressed) {
            mPaint.color = mPressedBorderColor
            mPaint.style = Paint.Style.FILL
            canvas?.drawCircle(radius, radius, radius - mBorderWidth, mPaint)
        }
        super.onDraw(canvas)
    }

    /**
     * 图形状态改变调用
     *
     */
    override fun drawableStateChanged() {
        super.drawableStateChanged()
        // 重新绘制控件
        invalidate()
    }

}